package study.算法.工具类;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author 刘伟涛
 * @Date 2024/3/12 15:16
 **/
public class Utils {


    /*
    * 思路，三个数字,{abc,efg,hij}
    * 回调次数取决于有几个数字。
    * aeh
    *
    * */
    public static List<String> letterCombinations(String digits) {
        List<String> combinations = new ArrayList<String>();
        if (digits.length() == 0) {
            return combinations;
        }
        HashMap<Character,String> hash = new HashMap<>();
        hash.put('2', "abc");
        hash.put('3', "def");
        hash.put('4', "ghi");
        hash.put('5', "jkl");
        hash.put('6', "mno");
        hash.put('7', "pqrs");
        hash.put('8', "tuv");
        hash.put('9', "wxyz");
        backtrack(combinations, hash, digits, 0, new StringBuffer());
        return combinations;
    }

    /*回调方法：多添加了index这个参数作为回调终止判断条件*/
    public static void backtrack(List<String> combinations, HashMap<Character, String> phoneMap, String digits, int index, StringBuffer combination) {
        //停止回调的判断
        if (index == digits.length()) {
            combinations.add(combination.toString());
        } else {
            char digit = digits.charAt(index);
            String letters = phoneMap.get(digit);
            int lettersCount = letters.length();
            for (int i = 0; i < lettersCount; i++) {
                combination.append(letters.charAt(i));
                backtrack(combinations, phoneMap, digits, index + 1, combination);
                //删除最后一个数字 例如输入2345，得adgj删除j。
                combination.deleteCharAt(index);
            }
        }
    }
}
